<?php
$cs = Yii::app()->clientScript;
if ($isNew)
{
    //add widget to page
    $pageId = $this->get('page_id', 0);
    $revision_id = $this->get('revision_id', 1);
    $container = $this->get('container', $container);
    $widgetLayoutId = $this->get('widget_layout_id', 0);
    if ($pageId && empty($container) === false)
    {
        $script = "
\$('#WidgetData_name').closest('form')
.append('<input type=\"hidden\" name=\"page_id\" value=\"{$pageId}\" />')
.append('<input type=\"hidden\" name=\"revision_id\" value=\"{$revision_id}\" />')
.append('<input type=\"hidden\" name=\"container\" value=\"{$container}\" />')
.append('<input type=\"hidden\" name=\"widget_layout_id\" value=\"{$widgetLayoutId}\" />');
        ";
        $cs->registerScript(__CLASS__.'AppendExtraData', $script);
    }
    if ($widget->type === WidgetDefinition::TYPE_STATIC)
    {
        $urlManager = new CUrlManager();
        $baseUrl = $urlManager->createUrl('/Core/service/ajax');
        $script = "
jQuery('.row .buttons').click(function(){
    var name = jQuery('#WidgetData_name').val();
    name = name.replace(/\s+/, '');
    if (name.length <= 0 )
    {
        alert('Name is required');
        return false;
    }
    var widget_id = parseInt(jQuery('#WidgetData_widget_id').val());
    var container = jQuery('#WidgetData_container').val();
    if (container == 'custom')
        container = jQuery('#WidgetData_containerCustom').val();
        
    var data = {
        'SID' : 'Cms.widgetData.staticNameExist', 
        'widget_id' : widget_id,
        'name' : name,
        'container' : container
    };
    var valid = true;
    jQuery.ajax({
        async : false,
        url : '{$baseUrl}',
        data : data,
        success: function(res){
            res = eval(res);
            if (res.errors != undefined && res.errors.ErrorCode != undefined) {
                var message = 'Error';
                if (jQuery.isArray(res.errors.ErrorCode))
                    message = res.errors.ErrorCode.join('. ');
                alert(message);
                valid = false;
            }
        }
    });
    return valid;
});
";
        $cs->registerScript(__CLASS__.'#ValidName', $script);
    }
}

$script = "
jQuery('.hidden-field').each(function(){
    jQuery('form .row:last').before(jQuery(this));
});
jQuery('body').delegate('#WidgetData_container', 'change', function(){
    var container = jQuery(this).val();
    if (jQuery.inArray(container, ['cms-header','cms-footer']) == -1)
    {
        if (container == 'custom')
            jQuery('#WidgetData_containerCustom').show();
    }
    else
    {
        jQuery('#WidgetData_containerCustom').hide();
    }
});
jQuery('#WidgetData_container').trigger('change');
";
$cs->registerScript(__CLASS__.'#RegisterHiddenField', $script);
?>

<h2><?php echo $isNew ? 'Create' : 'Update';?> <?php echo isset($widget) && is_object($widget) ? $widget->name : '';?> content</h2>

<?php
$form = $this->beginWidget('Admin.components.DynamicForm',array(
    'attributes' => $attributes,
    'config' => $config
));
    $form->render();
?>
    <div class="row hidden-field">
        <?php echo CHtml::label('Container', 'WidgetData_container'); ?>
        <?php echo CHtml::dropDownList('WidgetData[container]', in_array($container, array('cms-header', 'cms-footer')) ? $container : 'custom', array('cms-header'=>'Header','cms-footer'=>'Footer','custom'=>'Custom'), array('prompt'=>'---Select---'));?>
        <?php echo CHtml::textField('WidgetData[containerCustom]', (in_array($container, array('cms-header', 'cms-footer')) ? '' : $container), array('size'=>60,'maxlength'=>100,'style'=>'display:none;')); ?>
    </div>
<?php
    echo CHtml::hiddenField('WidgetData[type]', $widget->type, array('class'=>'hidden-field'));
$this->endWidget();
?>

<script type="text/javascript">
function duplicate(me){
    jQuery('form').sortable('destroy');
    parent = $(me).closest('.widget-group');
    if (parent.siblings('.widget-group').size() == 0)
    {
        $('.up', parent).css('cssText', 'display: block !important');
        $('.down', parent).css('cssText', 'display: block !important');
        $('.remove', parent).css('cssText', 'display: block !important');
    }
    duplicated = parent.clone();
    parent.after(duplicated);
    jQuery('form').sortable({'items':'fieldset','handle':'.drag-handle'});
    return false;
}

function remove(me){
    group = $(me).closest('.widget-group');
    if (group.size())
    {
        var sibling_size = group.siblings('.widget-group').size();
        if (sibling_size)
        {
            if (sibling_size == 1)
            {
                var sibling = group.siblings('.widget-group');
                $('.up', sibling).css('cssText', 'display: none !important');
                $('.down', sibling).css('cssText', 'display: none !important');
                $('.remove', sibling).css('cssText', 'display: none !important');
            }
            group.remove();
        }
        else
        {
            alert('There must be at least on set of '+group.attr('class').replace('widget-group fieldset_','')+' field(s).');
        }
    }
    else
        alert('There must be at least on set of '+group.attr('class').replace('widget-group fieldset_','')+' field(s).');
        
    return false;
}
$(function(){
    parent.$('#sb-nav-save-form').unbind('click').bind('click', function(){
        //layout
        if (jQuery('.scroll-content-item').size())
        {
            var widget_layout_id = jQuery('.scroll-content-item input:checked').val();
            widget_layout_id = parseInt(widget_layout_id);
            var widget_layout_element = $('<input name="widget_layout_id" value="'+widget_layout_id+'" />');
            $('form').append(widget_layout_element);
        }        
        
        var items_length = $('.page_widget_id').size();
        var items_checked = $('.page_widget_id:checked');
        if (items_length == items_checked.size())
        {
            if (items_length > 1)
            {
                if (confirm('Are you sure to apply changes to all pages.'))
                    $('form').submit();
            }
            else
                $('form').submit();
        }
        else
        {
            var pages = [];
            var update_page_widgets = [];
            $.each(items_checked, function(index){
                update_page_widgets.push($(this).val());
                pages.push((index+1)+'. '+$(this).next('label').text());
            });
            if (update_page_widgets.length == 0)
            {
                var panel = $('.page_widget_id').closest('.ui-tabs-panel');
                if (panel.is(':hidden'))
                {
                    var index = panel.prevAll('div.ui-tabs-panel').size();
                    panel.closest('.ui-tabs').tabs('select', index);
                }
                alert('Please select least one page.');
            }
            else if (confirm('Are you sure to apply changes to following pages:'+"\n"+pages.join("\n")))
            {
                var page_widget_element = $('<input name="update_page_widgets" value="'+update_page_widgets.join(',')+'" />');
                $('form')
                    .append(page_widget_element)
                    .submit();
            }
        }
        
        return false;
    })
        .parent().show();
});
</script>